package com.xzy.spring.main;

import com.xzy.spring.business.serviceimpl.UserServiceImpl;
import com.xzy.spring.config.AutowiredConfig;
import com.xzy.spring.demo.aware.MyAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author xzy
 * @date 2021-02-13 21:02
 * 说明：
 */
public class AutowiredMain {
    public static void main(String[] args) {
        frameworkComponents();
    }

    /**
     * 自动装配与属性名：自动装配时如果IOC容器中存在同类型的组件，则寻找组件名与属性名相同的组件。
     *
     * @apiNote - 测试前需要检查AutowiredConfig类userRepositoryPrimary()方法上的@Primary注解是否去除
     * @see AutowiredConfig
     */
    private static void autowiredAndPropertyName() {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = getAnnotationConfigApplicationContext();
        UserServiceImpl userServiceImpl = annotationConfigApplicationContext.getBean("userServiceImpl", UserServiceImpl.class);
        System.out.println("属性userRepository1注入的组件：" + userServiceImpl.getUserRepository1());
        System.out.println("属性userRepository2注入的组件：" + userServiceImpl.getUserRepository2());
    }

    /**
     * 使用@Qualifier挑选注入的组件——通过限制组件名称
     */
    private static void autowiredAndQualifier() {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = getAnnotationConfigApplicationContext();
        UserServiceImpl userServiceImpl = annotationConfigApplicationContext.getBean("userServiceImpl", UserServiceImpl.class);
        System.out.println("属性userRepository注入的组件：" + userServiceImpl.getUserRepository());
    }

    /**
     * 首选组件
     *
     * @apiNote - 测试前需要检查AutowiredConfig类userRepositoryPrimary()方法上的@Primary注解是否添加
     * @see AutowiredConfig
     */
    private static void autowiredAndPrimary() {
        autowiredAndPropertyName();
    }

    /**
     * 获取框架底层组件
     */
    private static void frameworkComponents() {
        MyAware frameworkComponents = getAnnotationConfigApplicationContext()
                .getBean("frameworkComponents", MyAware.class);

        ApplicationContext applicationContext = frameworkComponents.getApplicationContext();
        BeanFactory beanFactory = frameworkComponents.getBeanFactory();
    }

    /*Supporters*/

    private static AnnotationConfigApplicationContext getAnnotationConfigApplicationContext() {
        return new AnnotationConfigApplicationContext(AutowiredConfig.class);
    }

    private static void printBeans(ApplicationContext applicationContext) {
        System.out.println("\n已注册的组件：");
        for (String beanDefinitionName : applicationContext.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
        System.out.println("");
    }
}
